<?php


namespace app\admin\service;

use app\admin\model\Admin;
use app\admin\model\AdminMenu;

use function now_time;

class AdminMenuService
{

    /**
     * 菜单列表
     *
     * @return array|\think\Paginator
     */
    static public function cmsList($extendQueryHelper, $data)
    {
        $query = AdminMenu::build()
                          ->with(['parentMenu'])
                          ->where($extendQueryHelper->where)
                          ->order($extendQueryHelper->sort, $extendQueryHelper->order)
                          ->equal('level')
                          ->keyWrod('menu_name')
                          ->where('status', 1);
        return $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
    }

    /**
     * 修改菜单
     *
     * @param $request
     *
     */
    static public function cmsEdit($request)
    {
        $menu_id = $request['menu_id'];
        unset($request['menu_id']);
        $model = AdminMenu::build()
                          ->find($menu_id);
        $model
            ->save($request);
        return $model;
    }

    /**
     * 删除菜单
     *
     * @param $menu_id
     *
     * @return AdminMenu
     */
    static public function cmsDelete($menu_id)
    {
        return AdminMenu::build()
                        ->where('menu_id', $menu_id)
                        ->update(['status' => 0]);
    }

    /**
     * 添加菜单
     *
     * @param $request
     *
     */
    static public function cmsAdd($request)
    {
        $request['create_time'] = now_time(time());
        $model = new AdminMenu();

        $model->save($request);
        return $model;
    }

    /**
     * 菜单详情
     *
     * @param $menu_id
     *
     * @return array
     */
    static public function cmsDetail($menu_id)
    {
        return AdminMenu::build()
                        ->whereIn('menu_id', $menu_id)
                        ->find();
    }

    //获取接口权限
    public static function getApiAuth()
    {
        $list = AdminMenu::build()
                         ->where('type', 3)
                         ->where('status', 1)
                         ->whereNotNull('menu_url')
                         ->column('menu_name', 'menu_url');
        $commonList = AdminMenu::build()
                               ->where('type', 3)
                               ->where('status', 1)
                               ->where('is_common', 1)
                               ->column('menu_name', 'menu_url');
        $list = array_merge($list, $commonList);
        $list = array_change_key_case($list, CASE_UPPER);
        return $list;
    }
}